<template>
  <div class="write-rebate">
    <!-- 操作結果提示 -->
    <msg v-if="doneShow" class="done-msg" :icon="doneIcon">
      <template slot="buttons">
        <router-link class="success-btn" v-if="doneIcon === 'success'" :to="{ name: 'InitiateApplication'}">
          返回首页
        </router-link>
        <a class="success-btn" v-else @click="closeDoneInfo">返回密钥申请</a>
      </template>
      <template slot="description">
        <p class="title">{{doneTitle}}</p>
        <p>{{doneMsg}}</p>
      </template>
    </msg>
    <div class="scroll-box" v-show="!doneShow">
      <!-- 文本域 -->
      <my-write-myKey-info ref="myKey"></my-write-myKey-info>
      <!-- 附件 -->
      <!-- <my-annex ref="annex"></my-annex> -->
      <!-- 抄送人 -->
      <my-make-copy ref="makeCopy" :makeCopyParams="makeCopyParams"></my-make-copy>
    </div>
    <!-- 底部組件 -->
    <my-bottom-submit v-if="!doneShow" @click.native="applySubmit"></my-bottom-submit>
    <!-- 加载中 -->
    <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="turndownShow"
        class="turndown-confirm" title="提示" confirm-text="确认" :show-cancel-button="false">
        <p>{{turndownText}}</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  // import Approver from '@/components/ApplyWrite/Approver.vue';
  import MakeCopy from '@/components/ApplyWrite/MakeCopy.vue';
  import BottomSubmit from '@/components/Bottom/BottomSubmit.vue';
  import MyWriteKeyInfo from '@/components/ApplyWrite/WriteKeyInfo.vue';
  import { Msg, Loading, Confirm, TransferDom } from 'vux';
  import qs from 'qs';
  export default {
    name: 'WriteKey',
    data () {
      return {
        defaultMakeCopyPersonsId:"11398",
        doneIcon: '',
        doneTitle: '',
        doneMsg: '',
        doneShow: false,
        loadingShow: false,
        required: ['clientName','keyPassword','mobilePhone','PropertyID',],
        turndownShow: false,
        turndownText: '',
        makeCopyParams: [],
        canSubmit:false
      };
    },
    directives: {
      TransferDom
    },
    components: {
      Loading,
      Msg,
      Confirm,
      'my-make-copy': MakeCopy,
      'my-bottom-submit': BottomSubmit,
      'my-write-myKey-info': MyWriteKeyInfo,
      // 'my-annex': ()=>import('@/components/ApplyWrite/Annex.vue')
    },
    async mounted () {
      await this.pageInit();
      if (this.$refs.makeCopy.resultList.length === 0) {
        this.$refs.makeCopy.resultList = this.makeCopyParams;
      }
    },
    watch: {
      $route (to, from) {
        setTimeout(() => {
          this.loadingShow = false;
          this.changeDoneInfo(false);
        }, 500);
        this.pageInit(to, from);
      }
    },
    methods: {
      // 頁面初始化
      pageInit: async function (to, from) {
        // console.log("to",to,"from",from)
        let isHomeToThisPage;
        if (to && from) {
          isHomeToThisPage = from.name === 'InitiateApplication' && this.$route.name === 'WriteKey';
        }
        let isReApplyToThisPage = this.$route.query.applyInfo;
        if (isHomeToThisPage) {


          this.$refs.myKey.keyForm.clientName = '';       
          this.$refs.myKey.keyForm.keyPassword = '';       
          this.$refs.myKey.keyForm.areaCode = '+853';
          this.$refs.myKey.keyForm.mobilePhone = '';
          this.$refs.myKey.keyForm.PropertyID = '';             //楼盘编号
          this.$refs.myKey.keyForm.remarks = '';
          this.$refs.makeCopy.resultList = [];
          this.makeCopyParams = await this.getDefaultMakeCopy();
          this.$refs.myKey.editApplyReason = '';
          this.$refs.myKey.reApplyReason = '';

          if (this.$route.query.titleName === '修改申请') {
            // this.$refs.askLeaveInfo.reApplyReasonShow = true;
            this.$refs.myKey.editApplyReason = '';
            this.required.push('EditApplyReason');
            this.$refs.myKey.changeApplyType = '修改申请原因';
          } else if (params.IsReApply === true) {
            this.$refs.myKey.reApplyReason = '';
            this.required.push('ReApplyReason');
            this.$refs.myKey.changeApplyType = '重新申请原因';
          }

          // this.required.pop();
        } else if (from && from.name === 'SelectPerson' && this.$route.name === 'WriteKey') {
        } else if (isReApplyToThisPage && this.$route.name === 'WriteKey') {
          let params = JSON.parse(this.$route.query.applyInfo);
          this.makeCopyParams = await this.getDefaultMakeCopy();
          let copiers = params.Copiers.slice(1, params.Copiers.length); // 正式
          // let copiers = params.Copiers; // 测试
          if (copiers.length !== 0) {
            this.getReApplyMakeCopy(copiers);
          }
          this.$refs.myKey.keyForm.clientName = params.Content.clientName;
          this.$refs.myKey.keyForm.keyPassword = params.Content.keyPassword;
          this.$refs.myKey.keyForm.areaCode = params.Content.areaCode;
          this.$refs.myKey.keyForm.mobilePhone = params.Content.mobilePhone;
          this.$refs.myKey.keyForm.PropertyID = params.Content.PropertyID;
          this.$refs.myKey.keyForm.remarks = params.Content.remarks;
          
          if (this.$route.query.titleName === '修改申请') {
            // this.$refs.askLeaveInfo.reApplyReasonShow = true;
            this.$refs.myKey.editApplyReason = '';
            this.required.push('EditApplyReason');
            this.$refs.myKey.changeApplyType = '修改申请原因';
          } else if (params.IsReApply === true) {
            this.$refs.myKey.reApplyReason = '';
            this.required.push('ReApplyReason');
            this.$refs.myKey.changeApplyType = '重新申请原因';
          }
        } else {
          this.makeCopyParams = await this.getDefaultMakeCopy();
        }
      },
      authPhone(reg,mobile) {
        // /^[1][3-8]\d{9}$|^([6|9])\d{7}$|^[0][9]\d{8}$|^[6]([8|6])\d{5}$/
        if (!(reg.test(mobile))) {
          return false
        }else {
          return true
        }
      },
      // 提交事件
      applySubmit: function () {
        if (this.loadingShow) {
          return false;
        }
        let ContentData = {
          ...this.$refs.myKey.keyForm
        };
        if (this.$refs.myKey.changeApplyType === '重新申请原因') {
          ContentData.ReApplyReason = this.$refs.myKey.reApplyReason;
        }
        if (this.$refs.myKey.changeApplyType === '修改申请原因') {
          ContentData.EditApplyReason = this.$refs.myKey.editApplyReason;
        }
        let postData = {
          data: {
            Type: 4,
            CreatedStaffNo: this.getUserInfo().StaffNo,
            Copiers: this.parseCopiers(),
            Content: JSON.stringify(ContentData)
          }
        };
        for (let prop in this.required) {
          let propName = this.required[prop];
          if (ContentData[propName] === '' || ContentData[propName] === null) {
            this.turndownShow = true;
            this.turndownText = '请输入必填項';
            return false;
          }
        }
        let phoneReg = /^[1][3-8]\d{9}$|^([6|9])\d{7}$|^[0][9]\d{8}$|^[6]([8|6])\d{5}$/
        if(!this.authPhone(phoneReg,ContentData.mobilePhone)){
          this.turndownShow = true;
          this.turndownText = '请正确输入电话号码'; 
          return false
        }
        this.loadingShow = true;
        if (this.$route.query && this.$route.query.titleName === '修改申请') {
          postData.data.KeyId = JSON.parse(this.$route.query.applyInfo).KeyId;
          this.editRequest(postData);
        } else {
          if (this.$route.query.applyInfo !== undefined) {
            let query = JSON.parse(this.$route.query.applyInfo);
            if (query.IsReApply !== undefined) {
              postData.data.IsReApply = query.IsReApply;
            }
          }
          this.createRequest(postData);
        }
      },
      editRequest: function (params) {
        this.loadingShow = true;
        this.axios.post('/Process/EditAskForLeaveInfo', qs.stringify(params))
        .then((res) => {
          if (res.data.IsSuccess === true) {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'success', '提交修改成功', '你的申请已成功提交修改，等待上级领导审批中');
          } else {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申请未能成功提交修改，具体错误：${res.data.ExMessage}`);
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申请未能成功提交修改，具体错误：${err}`);
        });
      },
      createRequest(params){
        this.loadingShow = true;
        this.axios.post('/Process/Create', qs.stringify(params))
        .then((res) => {
          if (res.data.IsSuccess === true) {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'success', '提交申请成功', '你的申請已成功提交，等待上级领导审批中');
          } else {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${res.data.ExMessage}`);
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${err}`);
        });
      },
      // 抄送人格式轉換 （只POST StaffNo）
      parseCopiers: function () {
        let copiers = this.$refs.makeCopy.resultList;
        let newCopiers = [];
        copiers.forEach((item) => {
          newCopiers.push({StaffNo: item.userid});
        });
        return newCopiers;
      },
      changeDoneInfo: function (status, iconType, title, msg) {
        this.doneIcon = iconType;
        this.doneTitle = title;
        this.doneMsg = msg;
        this.doneShow = status;
      },
      closeDoneInfo: function () {
        this.changeDoneInfo(false, '', '', '');
      },
      getDefaultMakeCopy: async function () {
        let postData = {
          data: {
            StaffNoArr:[{StaffNo:this.defaultMakeCopyPersonsId}]
          }
        };
        this.loadingShow = true;
        try {
          let res = await this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            res.data.data.Users[0]["checked"] = true;
            res.data.data.Users[0]["removeSwitch"] = false;
            let makeCopyArr = res.data.data.Users;
            return makeCopyArr;
          } else {
            this.turndownShow = true;
            this.turndownText = '获取默认抄送人失败';
            return [];
          }
        } catch(err){
          this.turndownShow = true;
          this.turndownText = '获取默认抄送人失败';
        } finally{
          this.loadingShow = false;
        }
      
        // return [
        //   {
        //     userid: '10026',
        //     'name': 'Jacky Shek',
        //     'department': [2, 6, 12, 5],
        //     'position': '中原澳門及橫琴高級董事',
        //     'mobile': '98386138',
        //     'gender': 1,
        //     'email': '',
        //     'weixinid': null,
        //     'avatar': 'http://shp.qpic.cn/bizmp/j9Y9icaeLJ2Me8j5J5bHx5uRl8tevnxaMD2QNeWWhzNpj3LJltY5A9g/',
        //     'status': 1,
        //     'extattr': {
        //       'attrs': []
        //     },
        //     'checked': true,
        //     'removeSwitch': false
        //   }
        // ];
      },
      getReApplyMakeCopy: function (staffNoArr) {
        let postData = {
          data: {
            StaffNoArr: staffNoArr
          }
        };
        this.loadingShow = true;
        return this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
        .then((res) => {
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            this.makeCopyParams = this.makeCopyParams.concat(res.data.data.Users);
            this.$refs.makeCopy.resultList = this.makeCopyParams;
          } else {
            this.turndownShow = true;
            this.turndownText = '获取抄送人失败';
          }
        })
        .catch(() => {
          this.loadingShow = false;
          this.turndownShow = true;
          this.turndownText = '获取抄送人失败';
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .write-rebate {
    -webkit-overflow-scrolling: touch;
  }
</style>
